package core.server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public abstract class CoreServer {
	private ServerSocket serverSocket = null;
	private boolean isLoop = true;
	
	/**
	 * Xu ly su kien khi tao server thanh cong
	 */
	public abstract void onCreate();
	
	/**
	 * Xu ly su kien khi dong server tanh cong
	 */
	public abstract void onDisconnect();
	
	/**
	 * Xu ly su kien khi co loi
	 * @param e
	 */
	public abstract void onError(Exception e);
	
	/**
	 * Cai dat chi tiet xu ly cua server
	 * @param clientSocket
	 */
	public abstract void onLoop(Socket clientSocket);
	

	
	/**
	 * Khoi tao server voi cong truyen vao
	 * @param port
	 */
	public void create(int port){
		if (createServer(port)) {
			loop();
		}
	}

	/**
	 * Dong server
	 */
	public void close() {
		if (serverSocket != null) {
			try {
				serverSocket.close();
			} catch (IOException e) {
				onError(e);
			}
		}
	}
	
	public ServerSocket getServerSocket(){
		return serverSocket;
	}

	public void outLoop(){
		isLoop = false;
	}
	
	private boolean createServer(int port){
		if (serverSocket == null) {
			try {
				serverSocket = new ServerSocket(port);
				onCreate();
			} catch (IOException e) {
				onError(e);
				return false;
			}
		}
		return true;
	}
	
	/**
	 * Cong viec server
	 */
	private void loop(){
		while (isLoop) {
			try {
				Socket clientSocket = serverSocket.accept();
				onLoop(clientSocket);
			} catch (IOException e) {
				onError(e);
			}
		}
	}
}
